package com.girl.girl.controller;

import com.girl.girl.domain.Girl;
import com.girl.girl.domain.Result;
import com.girl.girl.repository.GirlReposties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import com.girl.girl.service.GirlService;
import java.util.List;

/**
 * Created by qxl on
 * 2018/7/2
 */

/**
 * Aop 是一种变成规范，与语言无关，是一种程序设计思想
 * 比如：面向过程的时候，if下雨，那么我打扫
 *       面向对面的时候，实例化天气对象-->下雨  实例我对象---》打扫
 * AOP换个角度看世界，换个姿态处理问题
 * 将通用逻辑从 业务逻辑中分离出来
 * 垂直水平划分： 请求接收，记录请求，处理网络请求，生成response,记录回复
 *              收到数据库操作请求， 记录请求， 增删改查 ，生成处理结果，记录回复
 *
 *   切面提取：处理请求的操作 和 处理结果的操作是通过的，
 *   从通过的业务逻辑中分离出来了
 *
 *
 *
 *
 */
@RestController
public class GirlController {

    private final static Logger logger = LoggerFactory.getLogger(GirlController.class);

    @Autowired
    private GirlReposties girlReposties;

    @Autowired
    private GirlService girlService;

    @GetMapping(value = "/girls")
    public List<Girl> girlList(){
        logger.info("girlList");
        return this.girlReposties.findAll();
    }

    /**
     * 追加一个女生
     * @param
     * @param
     * @return
     */
    @PostMapping(value = "/girl")
    public Result girlAdd(Girl girl, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return new Result(0,bindingResult.getFieldError().getDefaultMessage());
        }
        girl.setCupSize(girl.getCupSize());
        girl.setAge(girl.getAge());
        //添加
        Girl save = this.girlReposties.save(girl);
        if (null != save){
           return new Result(0,"成功",save);
        }
        return null;
    }
    //删除
    @DeleteMapping(value = "/girldelete/{id}")
    public void getGirlId(@PathVariable("id") Integer id){
        this.girlReposties.deleteById(id);
    }
    //通过年纪来查看
    @GetMapping(value = "/girlselectByAge")
    public List<Girl> grilListByAge(@RequestParam("age") Integer age){
        List<Girl> byAge = this.girlReposties.findByAge(age);
        if (! CollectionUtils.isEmpty(byAge)){
            return byAge;
        }
        return null;
    }
    @PutMapping(value = "/girlupdate/{id}")
    public Girl updateGirl(@PathVariable("id") Integer id,@RequestParam("cupSize") String cupSize,
                           @RequestParam("age") Integer age){
        //获取参数
        Girl girl = new Girl();
        girl.setId(id);
        //需要改变的值
        girl.setCupSize(cupSize);
        girl.setAge(age);
        Girl update = this.girlReposties.save(girl);
        if (null != update){
            return update;
        }
        return null;
    }

    @PostMapping(value = "/girls/two")
    public void girlTwo(){
        this.girlService.insertTwo();
    }

}
